package com.benin.sms.base

import android.Manifest
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import android.widget.EditText
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModel
import com.benin.sms.component.dialog.LoadingDialogipetrpide
import com.benin.sms.component.dialog.MessageDialog
import com.benin.sms.extipetrpide.canHideKeyboardipetrpide
import com.benin.sms.extipetrpide.hideKeyboardipetrpide
import com.benin.sms.extipetrpide.setFullScreenMode
import com.benin.sms.network.NetworkException
import com.vmadalin.easypermissions.EasyPermissions
import com.vmadalin.easypermissions.annotations.AfterPermissionGranted
import com.vmadalin.easypermissions.dialogs.DEFAULT_SETTINGS_REQ_CODE
import com.vmadalin.easypermissions.dialogs.SettingsDialog


const val REQ_CODE_PAGE_PERMISSION: Int = 200
const val REQ_CODE_PAGE_UNKNOW_SOURCES = 10087
const val REQ_CODE_ROLE_DIALER = 10088


abstract class BaseActivity : AppCompatActivity(), EasyPermissions.PermissionCallbacks,
    EasyPermissions.RationaleCallbacks {

    var ACTIVITY_TAG: String = ""

    private lateinit var mLoadingDialogipetrpide: LoadingDialogipetrpide
    private var mPermissionListipetrpide: Array<String>? = null
    private var mPermissionStatementipetrpide: String? = null
    private var mSavedInstanceState: Bundle? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        try {
            ACTIVITY_TAG = this::class.java.simpleName
            mSavedInstanceState = savedInstanceState

            setFullScreenMode()
            ACTIVITY_TAG = onBindingViewTag()
            setContentView(onBindingContentView())
            mLoadingDialogipetrpide = LoadingDialogipetrpide(this)
            setViewModelActionsipetrpide()
            onContentViewBinded()

        } catch (e: Exception) {
            //
        }
    }

    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        if (ev.action == MotionEvent.ACTION_DOWN) {
            val view = currentFocus
            if (view != null) {
                try {
                    if (canHideKeyboardipetrpide(view, ev)) {
                        hideKeyboardipetrpide()
                        val editText = view as EditText
                        editText.clearFocus()
                    }
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
            return super.dispatchTouchEvent(ev)
        }
        return window.superDispatchTouchEvent(ev) || onTouchEvent(ev)
    }

    override fun onResume() {
        super.onResume()
//        val gTypeipetrpide = "${this.javaClass.simpleName}_START".uppercase()
//        RepoTool.saveUserBuriedPointipetrpide(ToSaveUserBuriedPointTo(gTypeipetrpide))
    }

    override fun onPause() {
        super.onPause()
//        val gTypeipetrpide = "${this.javaClass.simpleName}_END".uppercase()
//        RepoTool.saveUserBuriedPointipetrpide(ToSaveUserBuriedPointTo(gTypeipetrpide))
    }

    /**绑定model*/
    protected abstract fun onBindingViewModel(): List<ViewModel>?

    /**绑定tag*/
    protected abstract fun onBindingViewTag(): String

    /**绑定视图开始*/
    protected abstract fun onBindingContentView(): View

    /**绑定视图开始*/
//    protected abstract fun onBindingContentLayoutId(): Int

    /**绑定视图完成*/
    protected abstract fun onContentViewBinded()

    private fun setViewModelActionsipetrpide() {
        val viewModelListipetrpide = onBindingViewModel()
        if (!(viewModelListipetrpide.isNullOrEmpty())) {
            viewModelListipetrpide.forEach {
                if (it is IBaseViewModelAction) {
                    it.getLoadingLiveDataipetrpide().observe(this) { showLoading ->
                        if (showLoading)
                            showLodingDialogipetrpide()
                        else
                            dismissLoadingDialogipetrpide()
                    }

                    it.getNetworkExceptionLiveDataipetrpide().observe(this) {
                        onHandleNetworkExceptonipetrpide(it)
                    }
                }
            }
        }
    }

    protected fun showLodingDialogipetrpide() {
        mLoadingDialogipetrpide.showDialogipetrpide(this)
    }

    protected fun dismissLoadingDialogipetrpide() {
        mLoadingDialogipetrpide.dismissDialogipetrpide()
    }

    /**交给子类去实现*/
    open fun onHandleNetworkExceptonipetrpide(networkExceptionipetrpide: NetworkException) {
        if (networkExceptionipetrpide.isAlteripetrpide()) {
            MessageDialog.showDialogipetrpide(supportFragmentManager, networkExceptionipetrpide.msg)
        } else {
            Toast.makeText(this, networkExceptionipetrpide.msg, Toast.LENGTH_LONG)
                .show()
        }
    }

    /**交给子类去实现*/
    open fun onPermissionsRequestAllPassipetrpide() {

    }

    /**交给子类去实现*/
    open fun onDialerRoleRequestAllPass() {

    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray,
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)
    }

    override fun onRationaleAccepted(requestCode: Int) {
        mPermissionStatementipetrpide?.let {
            mPermissionListipetrpide?.let { list ->
                startEasyPermissionsipetrpide(it, list)
            }
        }
    }

    override fun onRationaleDenied(requestCode: Int) {
    }

    override fun onPermissionsDenied(requestCode: Int, perms: List<String>) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            SettingsDialog.Builder(this).build().show()
        }
    }

    override fun onPermissionsGranted(requestCode: Int, perms: List<String>) {
    }

    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == DEFAULT_SETTINGS_REQ_CODE) {
            mPermissionStatementipetrpide?.let {
                mPermissionListipetrpide?.let { list ->
                    startEasyPermissionsipetrpide(it, list)
                }
            }
        } else if (requestCode == REQ_CODE_PAGE_UNKNOW_SOURCES) {
            requestLaunchPermissionsipetrpide()

        } else if (requestCode == REQ_CODE_ROLE_DIALER) {
            println("请求替换默认电话器返回")
            onDialerRoleRequestAllPass()
        }
    }

    @AfterPermissionGranted(REQ_CODE_PAGE_PERMISSION)
    fun onEasyPermissionsAllPassipetrpide() {
        onPermissionsRequestAllPassipetrpide()
    }

    open fun requestLaunchPermissionsipetrpide() {
        try {

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                startEasyPermissionsipetrpide(
                    "App requires some permissions",
                    arrayOf(
                        Manifest.permission.READ_SMS,
                        Manifest.permission.READ_PHONE_STATE,
                        Manifest.permission.READ_CONTACTS,
                        Manifest.permission.POST_NOTIFICATIONS
                    )
                )
            }else{
                startEasyPermissionsipetrpide(
                    "App requires some permissions",
                    arrayOf(
                        Manifest.permission.READ_SMS,
                        Manifest.permission.READ_PHONE_STATE,
                        Manifest.permission.READ_CONTACTS
                    )
                )
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun startEasyPermissionsipetrpide(
        reqStatementipetrpide: String,
        permissionListipetrpide: Array<String>
    ) {
        mPermissionStatementipetrpide = reqStatementipetrpide
        mPermissionListipetrpide = permissionListipetrpide

        EasyPermissions.requestPermissions(
            this,
            reqStatementipetrpide,
            REQ_CODE_PAGE_PERMISSION,
            *permissionListipetrpide
        )
    }

    fun getNeedPermissions() {
        requestLaunchPermissionsipetrpide()
    }

}